<?php

namespace app\admin\service;

use app\common\Error;
use app\model\User;
use app\model\OfficialAccounts;
use app\model\WatchPayRecord;
use app\model\PayRecord;
use app\model\Records;
use app\model\Videos;
use app\model\VideoDetails;
use app\model\Admin;
use app\model\AdminRule;
use app\model\Proposal;
use app\model\Applet;
use app\model\Partners;
use app\model\Company;
use app\model\UserRechargeConsumeAnalysis;
use app\model\DeliveryData;
use app\model\GiveUserMoneyRecord;

class UserService
{
    private $model;
    private $officialAccountsModel;
    private $watchPayRecordModel;
    private $payRecordmodel;
    private $recordsModel;
    private $videoModel;
    private $videoDetailsModel;
    private $adminModel;
    private $adminRuleModel;
    private $proposalModel;
    private $appletModel;
    private $partnersModel;
    private $companyModel;
    private $userRechargeConsumeAnalysisModel;
    private $deliveryDataModel;
    private $giveUserMoneyRecordModel;

    public function __construct(User $model, OfficialAccounts $officialAccountsModel, WatchPayRecord $watchPayRecordModel, PayRecord $payRecordmodel, Records $recordsModel, Videos $videoModel, VideoDetails $videoDetailsModel, Admin $adminModel, AdminRule $adminRuleModel, Proposal $proposalModel, Applet $appletModel, Partners $partnersModel, Company $companyModel, UserRechargeConsumeAnalysis $userRechargeConsumeAnalysisModel, DeliveryData $deliveryDataModel, GiveUserMoneyRecord $giveUserMoneyRecordModel)
    {
        $this->model = $model;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->payRecordmodel = $payRecordmodel;
        $this->recordsModel = $recordsModel;
        $this->videoModel = $videoModel;
        $this->videoDetailsModel = $videoDetailsModel;
        $this->adminModel = $adminModel;
        $this->adminRuleModel = $adminRuleModel;
        $this->proposalModel = $proposalModel;
        $this->appletModel = $appletModel;
        $this->partnersModel = $partnersModel;
        $this->companyModel = $companyModel;
        $this->userRechargeConsumeAnalysisModel = $userRechargeConsumeAnalysisModel;
        $this->deliveryDataModel = $deliveryDataModel;
        $this->giveUserMoneyRecordModel = $giveUserMoneyRecordModel;
    }

    // 获取用户列表
    public function getUserList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where[] = ['is_delete', '=', 0];

        // 用户id搜索
        if (!empty($params['id'])) {
            $where[] = ['id', '=', $params['id']];
        }

        if (!empty($params['open_id'])) {
            $where[] = ['open_id', '=', $params['open_id']];
        }

        if (!empty($params['official_account_id'])) {
            $where[] = ['official_account_id', '=', $params['official_account_id']];
        }

        if (!empty($params['applet_id'])) {
            $where[] = ['applet_id', '=', $params['applet_id']];
        }

        if (!empty($params['start_date'])) {
            $startDate = strtotime($params['start_date']);
            $where[] = ['created_at', '>', $startDate];
        }

        if (!empty($params['end_date'])) {
            $endDate = strtotime($params['end_date'] . ' 23:59:59');
            $where[] = ['created_at', '<', $endDate];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, user_name, official_account_id, applet_id, avatar, is_delete, official_account_created_at, created_at, activation_time, link_id, status, closing_time, official_account_open_id, mobile_system, last_login_time, first_charge_date, money, is_members, expiration_time');

        if (!empty($data['data'])) {

            // 公众号名称
            $officialAccountIds = array_column($data['data'], 'official_account_id');
            $officialAccountsData = $this->officialAccountsModel->getDataByWhere(['id' => $officialAccountIds], 'id, name');
            $officialAccounts = array_column($officialAccountsData, 'name', 'id');

            // 小程序名称
            $appletIds = array_column($data['data'], 'applet_id');
            $appletData = $this->appletModel->getDataByWhere(['id' => $appletIds], 'id, name');
            $applet = array_column($appletData, 'name', 'id');

            foreach ($data['data'] as $key => $item) {

                $data['data'][$key]['official_account_name'] = empty($officialAccounts[$item['official_account_id']]) ? '' : $officialAccounts[$item['official_account_id']];

                $data['data'][$key]['applet_name'] = empty($applet[$item['applet_id']]) ? '' : $applet[$item['applet_id']];
            }
        }

        return $data;
    }

    // 获取用户详情
    public function getUserDetail($id)
    {
        $fields = 'id, user_name, official_account_open_id, open_id, money, official_account_id';
        $data = $this->model->getInfoById($id, $fields);

        $officialAccount = $this->officialAccountsModel->getInfoByWhere(['id' => $data['official_account_id']], 'name');
        $data['official_account_name'] = !empty($officialAccount['name']) ? $officialAccount['name'] : '';

        // 充值数
        $data['recharge_number'] = $this->payRecordmodel->getCount(['uid' => $id]);
        // 观看数
        $data['watch_number'] = $this->recordsModel->getCount(['uid' => $id]);

        return $data;
    }

    // 获取用户的消费记录
    public function getUserConsumeRecord($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->watchPayRecordModel->getPagingDataByWhere(['uid' => $params['id']], $page, $limit, 'id, video_id, video_detail_id, money, created_at');

        if (!empty($data['data'])) {
            $videoIds = $videoDetailIds = [];
            foreach ($data['data'] as $item) {
                $videoIds[] = $item['video_id'];
                $videoDetailIds[] = $item['video_detail_id'];
            }

            $videoData = $this->videoModel->getDataByWhere(['id' => $videoIds], 'id, name');
            $videoResult = array_column($videoData, 'name', 'id');
            $videoDetailData = $this->videoDetailsModel->getInfoByIds($videoDetailIds, 'id, sort');
            $videoDetailResult = array_column($videoDetailData, 'sort', 'id');

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['video_name'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']];
                $data['data'][$key]['video_detail_name'] = empty($videoDetailResult[$item['video_detail_id']]) ? '' : $videoDetailResult[$item['video_detail_id']];
            }
        }

        return $data;
    }

    // 获取用户的充值记录
    public function getUserRechargeRecord($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->payRecordmodel->getPagingDataByWhere(['uid' => $params['id']], $page, $limit, 'id, video_id, type, name, total_fee, created_at, status, order_no, wechat_order_no, platform_order_no, pay_type, pay_merchant');

        return $data;
    }

    // 获取用户的观看记录
    public function getUserWatchRecord($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->recordsModel->getDataByUid($params['id'], $page, $limit, 'id, video_id, video_detail_id, created_at');

        if (!empty($data['data'])) {
            $videoIds = $videoDetailIds = [];
            foreach ($data['data'] as $item) {
                $videoIds[] = $item['video_id'];
                $videoDetailIds[] = $item['video_detail_id'];
            }

            $videoData = $this->videoModel->getDataByWhere(['id' => $videoIds], 'id, name');
            $videoResult = array_column($videoData, 'name', 'id');

            $videoDetailData = $this->videoDetailsModel->getInfoByIds($videoDetailIds, 'id, sort');
            $videoDetailResult = array_column($videoDetailData, 'sort', 'id');

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['video_name'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']];
                $data['data'][$key]['video_detail_name'] = empty($videoDetailResult[$item['video_detail_id']]) ? '' : $videoDetailResult[$item['video_detail_id']];
            }
        }

        return $data;
    }

    /**
     * 获取管理员列表
     */
    public function getManagerList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = ['is_delete' => 1];
        $data = $this->adminModel->getPagingDataByWhere($where, $page, $limit, 'id, rule_id, name, profile_photo, fans_count, introduce, company_id, partner_id, status');

        $ruleIds = array_column($data['data'], 'rule_id');
        $ruleData = $this->adminRuleModel->getDataByWhere(['id' => $ruleIds], 'id, name');
        $ruleResult = array_column($ruleData, 'name', 'id');

        $company = $partners = [];

        $companyIds = array_column($data['data'], 'company_id');
        if (!empty($companyIds)) {
            $companyData = $this->companyModel->getDataByWhere(['id' => $companyIds]);
            $company = array_column($companyData, 'name', 'id');
        }

        $partnerIds = array_column($data['data'], 'partner_id');
        if (!empty($partnerIds)) {
            $partnerData = $this->partnersModel->getDataByWhere(['id' => $partnerIds]);
            $partners = array_column($partnerData, 'name', 'id');
        }

        foreach ($data['data'] as $key => $item) {
            $data['data'][$key]['rule_name'] = empty($ruleResult[$item['rule_id']]) ? '-' : $ruleResult[$item['rule_id']];
            $data['data'][$key]['company_name'] = empty($company[$item['company_id']]) ? '-' : $company[$item['company_id']];
            $data['data'][$key]['partner_name'] = empty($partners[$item['partner_id']]) ? '-' : $partners[$item['partner_id']];
        }

        return $data;
    }

    // 获取管理员详情
    public function getManagerDetail($id)
    {
        $data = $this->adminModel->getInfoById($id, 'id, rule_id, name, profile_photo, password, introduce, company_id, partner_id');
        return $data;
    }

    // 添加/修改管理员
    public function editManager($params)
    {
        if (empty($params['id'])) {
            $ossAccessAddress = config('filesystem.alioss.oss_access_address');
            if (strpos($params['profile_photo'], $ossAccessAddress['original_access_address']) !== false) {
                $params['profile_photo'] = str_replace($ossAccessAddress['original_access_address'], $ossAccessAddress['cdn_accelerated_domain'], $params['profile_photo']);
            }
            $params['created_at'] = time();
            $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);

            // 判断用户名有没有重名的
            $data = $this->adminModel->getInfoByWhere(['name' => $params['name']], 'id');
            if ($data) {
                return ['message' => Error::USERNAME_EXISTS];
            }
        } else {
            $params['updated_at'] = time();
            $data = $this->adminModel->getInfoById($params['id'], 'password');

            if ($data['password'] != $params['password']) { // 修改过
                $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
            }
        }

        $id = $this->adminModel->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }

    // 删除管理员
    public function deleteManager($id)
    {
        if (in_array($id, config('enum.admin_id'))) {
            return ['message' => Error::DELETE_MANAGER_ERROR_MESSAGE];
        }

        $count = $this->adminModel->getCounts();

        if ($count <= 1) {
            return false;
        }

        $bool = $this->adminModel->deleteAdminManager($id);

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 管理员下拉列表
    public function getManagerSelectList()
    {
        $where = ['status' => 1, 'is_delete' => 1];
        $data = $this->adminModel->getDataByWhere($where, 'id, name, profile_photo');
        return $data;
    }

    // 获取用户投诉建议列表
    public function getUserProposalList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        // 用户id搜索
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }

        if (!empty($params['applet_id'])) {
            $appletData = $this->appletModel->getInfoById($params['applet_id'], 'app_id');
            $where[] = ['app_id', '=', $appletData['app_id']];
        }

        if (!empty($params['start_date'])) {
            $startDate = strtotime($params['start_date']);
            $where[] = ['created_at', '>', $startDate];
        }

        if (!empty($params['end_date'])) {
            $endDate = strtotime($params['end_date'] . ' 23:59:59');
            $where[] = ['created_at', '<', $endDate];
        }

        $data = $this->proposalModel->getPagingDataByWhere($where, $page, $limit, 'id, app_id, uid, title, images, content, is_handle, created_at');
        if ($data['data']) {
            $appIds = array_column($data['data'], 'app_id');
            $appletData = $this->appletModel->getDataByWhere(['app_id' => $appIds], 'app_id, name');
            $applet = array_column($appletData, 'name', 'app_id');

            foreach ($data['data'] as $key => $item) {
                if ($item['images']) {
                    $data['data'][$key]['images'] = json_decode($item['images'], true);
                }
                $data['data'][$key]['applet_name'] = empty($applet[$item['app_id']]) ? '快应用' : $applet[$item['app_id']];
            }
        }
        return $data;
    }

    // 投诉建议详情
    public function getUserProposalDetail($id)
    {
        $data = $this->proposalModel->getInfoByWhere(['id' => $id], 'id, app_id, uid, title, images, content, is_handle');
        if ($data['images']) {
            $data['data'] = json_decode($data['images'], true);
        }
        return $data;
    }

    // 赠送用户K币/会员
    public function giveUserkCoins($params)
    {
        $id = $params['id'];
        $type = $params['type'];

        $userInfo = $this->model->getInfoById($id, 'money, expiration_time, is_members');

        if ($type == 1) {
            // 赠送K币
            $saveData = [
                'id' => $id,
                'money' => $userInfo['money'] + $params['money']
            ];
            $saveRecordData = [
                'uid' => $id,
                'type' => 1,
                'money' => $params['money'],
                'created_at' => time()
            ];
        } else {
            // 赠送会员
            // 延长会员过期时间
            // if ($userInfo['expiration_time'] && $userInfo['expiration_time'] > time()) {
            //     // 大于当前时间表示续费
            //     $expirationTime = strtotime('+1day', strtotime('+12' . ' month', $userInfo['expiration_time']));
            // } else {
            //     // 开通会员或会员已过期
            //     $expirationTime = strtotime(date('Y-m-d', strtotime('+1day', strtotime(date('Y-m-d', strtotime('+12' . ' month'))))));
            // }

            $saveData = [
                'id' => $id,
                'is_members'      => 1,
                'expiration_time' => strtotime($params['expiration_time'].' 23:59:59')
            ];

            $saveRecordData = [
                'uid' => $id,
                'type' => 2,
                'expiration_time' => $params['expiration_time'].' 23:59:59',
                'created_at' => time()
            ];
        }

        $saveMoneyBool = $this->model->edit($saveData);
        $this->giveUserMoneyRecordModel->edit($saveRecordData);

        if (!$saveMoneyBool) {
            return ['message' => Error::FAIL_MESSAGE];
        }
        return [];
    }

    // 用户分析
    public function getUserAnalysisData($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->userRechargeConsumeAnalysisModel->getPagingDataByWhere([], $page, $limit, 'date, activation_user_num, recharge_user_num, recharge_money, total_recharge, consume_k_coins, account_balance, per_capita_recharge, per_capita_consume');

        if ($data['data']) {
            $date = array_column($data['data'], 'date');
            $deliveryData = $this->deliveryDataModel->getDataByWhere(['date' => $date], 'date, total_recharge');
            $delivery = [];
            foreach ($deliveryData as $key => $value) {
                $delivery[$value['date']][] = $value['total_recharge'];
            }

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['date'] = substr($item['date'], 0, 4).'-'.substr($item['date'], 4, 2).'-'.substr($item['date'], 6, 2);
                $data['data'][$key]['total_recharge'] = !empty($delivery[$item['date']]) ? round(array_sum($delivery[$item['date']]), 2) : $item['total_recharge'];
            }
        }
        return $data;
    }

    // 开启状态账户可登录
    public function isSetStatus($params)
    {
        if (empty($params['id'])) {
            return false;
        }

        $id = $this->adminModel->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }
}
